<template>
  <div class="auth-container">
    <div
      class="container"
      :class="{
        'right-panel-active': showRegister,
        'extended-height': showRegister,
      }"
    >
      <!-- 登录表单 -->
      <div class="form-container sign-in-container">
        <el-form :model="loginForm" class="form" @submit.prevent="handleLogin">
          <h1>Welcome Back!</h1>
          <div class="social-container">
            <i class="iconfont icon-github"></i>
            <i class="iconfont icon-google"></i>
            <i class="iconfont icon-facebook"></i>
          </div>

          <el-form-item prop="account">
            <el-input
              v-model="loginForm.account"
              placeholder="请输入账号"
              :prefix-icon="User"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <div class="forgot-password">
            <a @click="showForgotPassword = true">忘记密码？</a>
          </div>
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            size="large"
            class="login-btn"
          >
            {{ loading ? "登录中..." : "立即登录" }}
          </el-button>
        </el-form>
      </div>

      <!-- 注册表单 -->
      <div class="form-container sign-up-container">
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          class="form"
          :rules="rules"
          @submit.prevent="handleRegister"
        >
          <h1>创建账号</h1>
          <span>注册您的个人信息</span>
          <!-- 第一列 -->
          <el-form-item prop="account">
            <!-- 提示注册框账号 -->
            <el-input
              v-model="registerForm.account"
              placeholder="请输入账号"
              :prefix-icon="User"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="nickname">
            <el-input
              v-model="registerForm.nickname"
              placeholder="请输入昵称"
              :prefix-icon="Avatar"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              :prefix-icon="Phone"
              size="large"
            />
          </el-form-item>
          <!-- 第二列 -->
          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              :prefix-icon="Message"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="请输入姓名"
              :prefix-icon="UserFilled"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="idcard">
            <el-input
              v-model="registerForm.idcard"
              placeholder="请输入身份证号"
              :prefix-icon="CreditCard"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="password" class="full-width">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword" class="full-width">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              :prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            size="large"
            class="login-btn"
          >
            {{ loading ? "注册中..." : "注册完成" }}
          </el-button>
        </el-form>
      </div>

      <!-- 切换覆盖层 -->
      <div class="overlay-container">
        <div class="overlay">
          <div class="overlay-panel overlay-left">
            <h1>欢迎回来!</h1>
            <p>请输入个人信息登录账号</p>
            <button class="ghost" @click="showRegister = false">SIGN IN</button>
          </div>
          <div class="overlay-panel overlay-right">
            <h1>新用户?</h1>
            <p>立即注册开启您的旅程</p>
            <button class="ghost" @click="showRegister = true">SIGN UP</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="showForgotPassword" title="重置密码" width="40%" center>
    <el-form
      label-width="120px"
      ref="forgotFormRef"
      :model="forgotForm"
      :rules="forgotRules"
    >
      <el-form-item label="账号" prop="account">
        <el-input
          v-model="forgotForm.account"
          placeholder="请输入您注册的账号"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="forgotForm.phone"
          placeholder="请输入您注册的手机号"
          :prefix-icon="Phone"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="forgotForm.email"
          placeholder="请输入您注册的邮箱地址"
          :prefix-icon="Message"
        />
      </el-form-item>
      <el-form-item label="身份证后六位" prop="idCardLastSix">
        <el-input
          v-model="forgotForm.idCardLastSix"
          placeholder="请输入您的身份证后六位"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="forgotForm.newPassword"
          type="password"
          placeholder="请输入您的新密码"
          :prefix-icon="Lock"
          size="large"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="forgotForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          :prefix-icon="Lock"
          size="large"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showForgotPassword = false">取消</el-button>
      <el-button
        type="primary"
        :loading="sending"
        @click="handleForgotPassword"
      >
        {{ sending ? "重置中..." : "重置密码" }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  User,
  Lock,
  Message,
  Phone,
  Avatar,
  CreditCard,
  UserFilled,
} from "@element-plus/icons-vue";
import { reactive, ref, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import api from "@/api";
import { ElMessage } from "element-plus";
import {
  validatePhone,
  validateEmail,
  validateIDCard,
} from "@/utils/validators";

const router = useRouter();
const route = useRoute();

// 保持原有登录逻辑
const loginForm = reactive({
  account: "",
  password: "",
});

const registerForm = reactive({
  account: "",
  nickname: "",
  phone: "",
  email: "",
  name: "",
  idcard: "",
  password: "",
  confirmPassword: "",
  roles: [
    {
      roleId: 1,
    },
  ],
});

const forgotForm = reactive({
  account: "",
  phone: "",
  email: "",
  idCardLastSix: "",
  newPassword: "",
});

const rules = reactive({
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 4, max: 20, message: "长度在4到20个字符", trigger: "blur" },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: validateEmail, trigger: "blur" },
  ],
  name: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  idcard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    { validator: validateIDCard, trigger: "blur" },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      validator: (_, value, callback) => {
        const strongRegex =
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/;
        if (!strongRegex.test(value)) {
          callback(new Error("需包含大小写字母和数字，至少8位"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
  ],
  newPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度至少6位", trigger: "blur" },
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "input"], // 增加输入时实时验证
    },
  ],
});
const forgotRules = reactive({
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: validateEmail, trigger: "blur" },
  ],
  idCardLastSix: [
    {
      required: true,
      message: "请输入身份证后6位",
      trigger: "blur",
    },
    {
      pattern: /^\d{6}$/,
      message: "请输入6位数字",
      trigger: "blur",
    },
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      validator: (_, value, callback) => {
        const strongRegex =
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d@$!%*?&]{8,}$/;
        if (!strongRegex.test(value)) {
          callback(new Error("需包含大小写字母和数字，至少8位"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const showForgotPassword = ref(false);

const sending = ref(false);

const showRegister = ref(false);
const loading = ref(false);
const registerFormRef = ref(null);
const forgotFormRef = ref(null);
const handleLogin = async () => {
  try {
    loading.value = true;
    if (loginForm.account == null) {
      ElMessage.error("账号不能为空");
    }
    if (loginForm.password == null) {
      ElMessage.error("密码不能为空");
    }

    // 调用接口（注意结构变化）
    const { data: token } = await api.auth.login(loginForm);

    // 验证Token格式
    if (typeof token !== "string" || !token.includes(".")) {
      throw new Error("无效的Token格式");
    }

    // 存储Token
    localStorage.setItem("token", token);
    console.log("存储的Token:", localStorage.getItem("token"));

    // 路由跳转（增加错误捕获）
    const redirectPath = route.query.redirect || "/home";
    await router.push(redirectPath).catch(() => {
      router.replace("/home"); // 容错处理
    });
    router.replace(route.query.redirect || "/home");
  } catch (error) {
    console.error("登录错误详情:", error);
    ElMessage.error(
      {
        无效的Token格式: "接口返回数据异常",
        "Network Error": "网络连接失败",
      }[error.message] || "登录失败"
    );
  } finally {
    loading.value = false;
  }
};

const handleRegister = async () => {
  console.log("注册数据:", registerForm);
  try {
    loading.value = true;
    await nextTick();

    if (!registerFormRef.value) {
      throw new Error("注册表单未正确初始化");
      return;
    }

    // 执行Element Plus表单验证
    const valid = await registerFormRef.value.validate().catch((err) => {
      console.error("表单验证失败:", err);
      return false;
    });
    if (!valid) {
      ElMessage.warning("请正确填写所有表单字段");
      return;
    }
    // 移除确认密码字段
    const { confirmPassword, ...submitData } = registerForm;
    // 发送注册请求
    const { data } = await api.auth.register(submitData);

    // 处理注册成功
    ElMessage.success("注册成功");
  } catch (error) {
    console.error("注册失败:", error);
    // 增强错误处理
    if (error.message.includes("表单引用")) {
      console.error("表单DOM未正确挂载");
      ElMessage.error("表单初始化失败，请刷新页面");
    }
    if (error.response?.data) {
      const { code, message } = error.response.data;
      if (code === 400) {
        ElMessage.error(message || "用户已存在");
      }
    } else {
      ElMessage.error(error.message || "网络请求失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleForgotPassword = async () => {
  try {
    sending.value = true;

    // 验证表单
    await forgotFormRef.value.validate();

    // 构建请求参数
    const params = {
      ...forgotForm,
      identityVerification: {
        phone: forgotForm.phone,
        email: forgotForm.email,
        idCardSuffix: forgotForm.idCardLastSix,
      },
    };

    // 调用重置接口
    const { data } = await api.auth.resetPwd(params);

    // 处理成功逻辑
    ElMessage.success("密码重置成功，请重新登录");
    showForgotPassword.value = false;

    // 清空表单
    forgotFormRef.value.resetFields();

    // 自动跳转登录
    showRegister.value = false;
  } catch (error) {
    console.error("密码重置失败:", error);

    // 错误分类处理
    const errorMessage =
      error.response?.data?.message || error.message || "密码重置失败";

    if (error.response?.status === 404) {
      ElMessage.error("用户信息不匹配");
    } else if (error.response?.status === 400) {
      ElMessage.error("验证信息有误");
    } else {
      ElMessage.error(errorMessage);
    }
  } finally {
    sending.value = false;
  }
};
</script>

<style scoped>
.auth-container {
  background: #f6f5f7;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: -20px 0 -50px;
}

.container {
  position: relative;
  width: 768px;
  max-width: 100%;
  min-height: 480px;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.1), 0 10px 10px rgba(0, 0, 0, 0.1);
}

.form-container {
  position: absolute;
  top: 0;
  height: 100%;
  padding: 40px;
  transition: all 0.6s ease-in-out;
}

.sign-in-container {
  left: 0;
  width: 50%;
  z-index: 2;
}

.sign-up-container {
  left: 0;
  width: 50%;
  opacity: 0;
  z-index: 1;
}

form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

h1 {
  font-weight: 500;
  margin: 0 0 15px;
}

span {
  font-size: 12px;
  color: #666;
  margin: 15px 0;
}

input {
  width: 100%;
  padding: 12px 15px;
  margin: 8px 0;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

button {
  background: #4b70e2;
  color: #fff;
  border: none;
  padding: 12px 45px;
  border-radius: 20px;
  margin-top: 15px;
  cursor: pointer;
  transition: transform 0.1s;
}

button:active {
  transform: scale(0.95);
}

.overlay-container {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: all 0.6s ease-in-out;
  z-index: 100;
}

.overlay {
  position: relative;
  left: -100%;
  width: 200%;
  height: 100%;
  background: linear-gradient(to right, #4b70e2, #6a82eb);
  transition: all 0.6s ease-in-out;
}

.overlay-panel {
  position: absolute;
  top: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 50%;
  height: 100%;
  padding: 0 40px;
  color: #fff;
  text-align: center;
}

.overlay-left {
  transform: translateX(-20%);
}

.overlay-right {
  right: 0;
  transform: translateX(0);
}

.ghost {
  background: transparent;
  border: 1px solid #fff;
}

/* 切换动画 */
.container.right-panel-active .sign-in-container {
  transform: translateX(100%);
  opacity: 0;
}

.container.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
}

.container.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

.container.right-panel-active .overlay {
  transform: translateX(50%);
}

.container.right-panel-active .overlay-left {
  transform: translateX(0);
}

.container.right-panel-active .overlay-right {
  transform: translateX(20%);
}

@media (max-width: 768px) {
  .container {
    width: 90%;
    min-height: 500px;
  }

  .form-container {
    width: 100%;
    height: 50%;
  }

  .overlay-container {
    width: 100%;
    height: 50%;
    left: 0;
    top: 50%;
  }
}
/* 增加容器高度 */
.container.extended-height {
  min-height: 700px;
}

/* 注册表单网格布局 */
.sign-up-container .form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px 30px;
  max-width: 800px;
}

/* 调整表单项间距 */
.el-form-item {
  margin-bottom: 18px;
}

/* 跨列显示的元素 */
.sign-up-container .login-btn {
  grid-column: span 2;
  justify-self: center;
  margin-top: 20px;
}

/* 调整输入框大小 */
.el-input {
  font-size: 15px;
}

/* 增加表单容器内边距 */
.form-container {
  padding: 50px 60px !important;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .sign-up-container .form {
    grid-template-columns: 1fr;
  }

  .sign-up-container .login-btn {
    grid-column: span 1;
  }

  .container.extended-height {
    min-height: 900px;
  }
}

/* 调整标题间距 */
.sign-up-container h1 {
  margin-bottom: 10px;
}

.sign-up-container > span {
  display: block;
  margin-bottom: 25px;
}

/* 增加输入框垂直间距 */
.el-input__wrapper {
  padding: 12px 15px;
  margin-top: 8px;
}
.auth-container {
  width: 100vw; /* 占据整个视口宽度 */
  padding: 20px; /* 增加呼吸空间 */
}

.container {
  width: 1000px; /* 加大基础宽度 */
  max-width: 90%; /* 保持响应式 */
  min-height: 600px; /* 增加垂直空间 */
}

/* 调整表单容器布局 */
.form-container {
  width: 50%;
  padding: 60px 80px; /* 增加内边距 */
}

/* 注册表单网格优化 */
.sign-up-container .form {
  grid-template-columns: repeat(2, minmax(200px, 1fr)); /* 设置最小列宽 */
  gap: 20px 40px; /* 增加行列间距 */
}

/* 输入框尺寸优化 */
.el-input {
  --el-input-height: 48px;
  font-size: 16px;
}

/* 按钮区域优化 */
.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
}

/* 覆盖层响应式调整 */
.overlay-panel {
  padding: 0 60px;
}

/* 大屏幕适配 */
@media (min-width: 1600px) {
  .container {
    width: 1200px;
  }

  .form-container {
    padding: 80px 100px;
  }
}

/* 移动端优化调整 */
@media (max-width: 768px) {
  .container {
    min-height: auto;
    flex-direction: column;
  }

  .form-container {
    width: 100%;
    padding: 40px 30px !important;
  }

  .sign-up-container .form {
    grid-template-columns: 1fr;
    gap: 15px;
  }
}
/* 忘记密码链接样式 */
.forgot-password {
  text-align: right;
  margin-top: 8px;
}

.forgot-password a {
  color: #4b70e2;
  font-size: 12px;
  cursor: pointer;
  text-decoration: underline;
}

/* 对话框响应式适配 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
  }

  :deep(.el-form-item__label) {
    width: 100% !important;
    text-align: left;
  }
}
/* 统一输入框尺寸 */
:deep(.el-input) {
  width: 320px; /* 固定输入框宽度 */
  --el-input-height: 48px;
  font-size: 16px;
  box-sizing: border-box;
}

/* 确保密码框图标不影响布局 */
:deep(.el-input__suffix) {
  right: 12px;
}

/* 修复密码可见切换图标对齐 */
:deep(.el-icon) {
  margin-left: 8px;
}

/* 移动端适配调整 */
@media (max-width: 768px) {
  :deep(.el-input) {
    --el-input-height: 44px;
    font-size: 15px;
  }
}
</style>
